package com.damon.android.interview.asynctask;

/**
 * Created by Damon.Han on 2018/10/11 0011.
 *
 * @author Damon
 */

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.damon.android.interview.R;

/**
 * A placeholder fragment containing a simple view.
 */
public class AsyncFragment extends Fragment implements View.OnClickListener {
    private Button button1;
    private ProgressBar progressBar;
    private TextView textView;
    private ImageView imageView;
    private Activity activity;
    private UpdateinfoTask updateinfoTask;
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    public AsyncFragment() {
    }

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static AsyncFragment newInstance() {
        AsyncFragment fragment = new AsyncFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_asynctask, container, false);
        button1 = rootView.findViewById(R.id.button1);
        progressBar = rootView.findViewById(R.id.progressBar);
        button1.setOnClickListener(this);
        imageView = rootView.findViewById(R.id.imageview);
        textView = rootView.findViewById(R.id.textView);
        activity = getActivity();
        progressBar.setProgress(0);
        return rootView;
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button1:
                updateinfoTask = new UpdateinfoTask(textView, progressBar);
                updateinfoTask.execute(0);
                break;
        }
    }

    //AsyncTask是基于线程池进行实现的,当一个线程没有结束时,后面的线程是不能执行的.
    @Override
    public void onPause() {
        super.onPause();
        if (updateinfoTask != null) {
            //cancel方法只是将对应的AsyncTask标记为cancelt状态,并不是真正的取消线程的执行.
            updateinfoTask.cancel(true);
        }
    }
}